package com.thz.admin.controller.gif;

import com.thz.common.constants.ConversionConstants;
import com.thz.common.dto.gif.ConversionVideoToGifRequestDTO;
import com.thz.common.dto.gif.ConversionVideoToGifResponseDTO;
import com.thz.common.result.Result;
import com.thz.common.utils.IpUtils;
import com.thz.system.service.gif.IConversionVideoToGifService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 视频转GIF控制器
 * 
 * @author THZ
 * @date 2025
 */
@Slf4j
@RestController
@RequestMapping("/api/conversion/videoToGif")
@Tag(name = "视频转换", description = "视频转GIF相关接口")
public class ConversionVideoToGifController {
    
    @Autowired
    private IConversionVideoToGifService conversionService;
    
    /**
     * 上传视频并转换为GIF（同步模式，已优化性能）
     * 
     * @param file 视频文件
     * @param width GIF宽度（可选）
     * @param height GIF高度（可选）
     * @param fps 帧率（1-30，默认10，超出范围自动修正）
     * @param startTime 开始时间（秒，可选）
     * @param duration 持续时间（秒，可选）
     * @param quality 质量（1-100，默认80，超出范围自动修正）
     * @param cropX 裁剪起始X坐标（可选）
     * @param cropY 裁剪起始Y坐标（可选）
     * @param cropWidth 裁剪宽度（可选）
     * @param cropHeight 裁剪高度（可选）
     * @param request HTTP请求对象
     * @return 转换结果
     */
    @PostMapping("/upload")
    @Operation(summary = "上传视频并转换为GIF", description = "上传视频文件并设置转换参数，转换为GIF格式（同步处理，返回转换结果）")
    public Result<ConversionVideoToGifResponseDTO> uploadAndConvert(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "width", required = false) Integer width,
            @RequestParam(value = "height", required = false) Integer height,
            @RequestParam(value = "fps", required = false, defaultValue = "10") Integer fps,
            @RequestParam(value = "startTime", required = false) Double startTime,
            @RequestParam(value = "duration", required = false) Double duration,
            @RequestParam(value = "quality", required = false, defaultValue = "80") Integer quality,
            @RequestParam(value = "cropX", required = false) Integer cropX,
            @RequestParam(value = "cropY", required = false) Integer cropY,
            @RequestParam(value = "cropWidth", required = false) Integer cropWidth,
            @RequestParam(value = "cropHeight", required = false) Integer cropHeight,
            HttpServletRequest request) {
        
        long totalStartTime = System.currentTimeMillis();
        
        log.info("收到视频转换请求: filename={}, size={}, contentType={}, fps={}, quality={}, cropX={}, cropY={}, cropWidth={}, cropHeight={}", 
                file.getOriginalFilename(), file.getSize(), file.getContentType(), fps, quality, cropX, cropY, cropWidth, cropHeight);
        
        // 快速验证文件是否为空
        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return Result.error("上传文件不能为空");
        }
        
        // 参数校验和修正
        fps = ConversionConstants.validateFps(fps);
        quality = ConversionConstants.validateQuality(quality);
        
        log.info("参数校验后: fps={}, quality={}", fps, quality);
        
        // 构建请求参数
        ConversionVideoToGifRequestDTO requestDTO = new ConversionVideoToGifRequestDTO();
        requestDTO.setWidth(width);
        requestDTO.setHeight(height);
        requestDTO.setFps(fps);
        requestDTO.setStartTime(startTime);
        requestDTO.setDuration(duration);
        requestDTO.setQuality(quality);
        requestDTO.setCropX(cropX);
        requestDTO.setCropY(cropY);
        requestDTO.setCropWidth(cropWidth);
        requestDTO.setCropHeight(cropHeight);
        
        // 获取客户端IP
        String ipAddress = IpUtils.getClientIp(request);
        
        // 使用同步服务执行转换（已优化性能）
        ConversionVideoToGifResponseDTO responseDTO = conversionService.convertVideoToGif(file, requestDTO, ipAddress);
        
        long totalTime = System.currentTimeMillis() - totalStartTime;
        log.info("【性能统计】视频转换完成 - 总耗时={}ms ({}秒)", totalTime, String.format("%.2f", totalTime / 1000.0));
        
        return Result.success(responseDTO);
    }
    
    /**
     * 查询转换记录
     * 
     * @param id 记录ID
     * @return 转换记录
     */
    @GetMapping("/{id:\\d+}")
    @Operation(summary = "查询转换记录", description = "根据ID查询转换记录详情")
    public Result<ConversionVideoToGifResponseDTO> getConversionRecord(@PathVariable Long id) {
        ConversionVideoToGifResponseDTO responseDTO = conversionService.getConversionRecord(id);
        return Result.success(responseDTO);
    }
    
    /**
     * 查询最近的转换记录
     * 
     * @param limit 数量限制（默认20）
     * @return 转换记录列表
     */
    @GetMapping("/recent")
    @Operation(summary = "查询最近的转换记录", description = "查询最近的转换记录列表")
    public Result<List<ConversionVideoToGifResponseDTO>> getRecentConversions(
            @RequestParam(value = "limit", required = false, defaultValue = "20") int limit) {
        List<ConversionVideoToGifResponseDTO> list = conversionService.getRecentConversions(limit);
        return Result.success(list);
    }
    
    /**
     * 删除转换记录
     * 
     * @param id 记录ID
     * @return 删除结果
     */
    @DeleteMapping("/{id:\\d+}")
    @Operation(summary = "删除转换记录", description = "删除转换记录及相关文件")
    public Result<Void> deleteConversion(@PathVariable Long id) {
        conversionService.deleteConversion(id);
        return Result.success("删除成功", null);
    }
    
}




